﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Deeper.Common;
using System.Text.RegularExpressions;

namespace Deeper.Engine
{

	public class Tag : IElement
	{
		public Document Host { protected set; get; }
		//public string Id { private set; get; }
		public string Name { protected set; get; }
		public string TagName { protected set; get; }
		public string Content { set; get; }
		public object DataSource { set; get; }

		public IList<IElement> Items { protected set; get; }
		public Tag(Document host, string tagName)
		{
			this.Host = host;
			TagName = tagName;
			Items = new List<IElement>();
		}

		protected object GetDatasource()
		{
			object obj = null;
			IList<string> list = null;
			int postion = Name.IndexOf('.');// Name.Substring(;
			if (postion > 0)
			{
				list = Name.Split('.').Where(s => s.Length > 0).ToList();
				obj = Host.Items[list[0]] ?? null;
				if (obj.IsNull())
					throw new Exception("变量名错误");
				obj = obj.GetSubPropertyValue(Name.Substring(postion + 1));
			}
			else
			{
				obj = Host.Items[Name] ?? null;
				if (obj.IsNull())
					throw new Exception("变量名错误");
			}
			return obj;
		}

		public virtual void ProcessEndTag(ref Match match)
		{ }

		/// <summary>
		/// 呈现本元素的数据
		/// </summary>
		/// <param name="writer"></param>
		public virtual void Render(System.IO.TextWriter writer)
		{
			Items.ToList().ForEach(s => s.Render(writer));
		}

		/// <summary>
		/// 返回文本字符
		/// </summary>
		/// <returns></returns>
		public override string ToString()
		{
			String text = string.Empty;
			Items.ToList().ForEach(s => text += s.ToString());
			return text.ToString();

		}
	}
}
